import { useState } from 'react';
import { history } from 'umi';
import { Form, message } from 'antd';
import { getExpertsManageSearchColumns, getExpertsManageTableColumns, getExpertsManageTableHeaderActions } from '../mconfig/index';
import { ExpertsManageService } from '../services/ManageService';
import { ExpertsDictionaryService } from '../services/DictionaryService';
import { getKeyRouter } from '@/utils';

const { success, warning } = message;

export function useExpertsManage(curRes, locationProps) {
  // 作废表单
  const [cancelForm] = Form.useForm();
  // 当前操作项信息
  const [info, setInfo] = useState<Record<string, any>>({});
  // 渲染作废状态
  const [isShowCancel, setIsShowCancel] = useState<boolean>(false);
  // 是否显示导入文件弹窗
  const [batchImport, setBatchImport] = useState<boolean>(false);
  // 是否显示导出文件弹窗
  const [exportState, setExportState] = useState<boolean>(false);
  // 表格选中内容
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 表格选中record
  const [selectRows, setSelectRows] = useState<Record<string, any>[]>([]);

  const { getExpertsManageService, cancelExpertsService, exportSearchParams } = ExpertsManageService();

  const { expertsManageRun, expertsManageDataSource, expertsManageLoading, expertsManageTableProps } = getExpertsManageService(curRes);

  const { cancelExpertsRun } = cancelExpertsService();

  const ExpertsDictionaryData = ExpertsDictionaryService();

  const fetchCancelExpert = async (params: Record<string, any>) => {
    const { msgFlag, msg } = await cancelExpertsRun(params);
    if (msgFlag) {
      success(msg);
      expertsManageRun({});
      setIsShowCancel(false);
    } else {
      warning(msg);
    }
  };

  /**确定作废 */
  const cancelSubmit = async () => {
    const result = await cancelForm.validateFields();
    const params = {
      id: info.id,
      versionNum: info.versionNum,
      ...result,
    };
    fetchCancelExpert(params);
  };

  /**
   * @operation
   * @description 管理页操作事件
   */
  const operation = {
    onView: (record: Record<string, any>) => {
      history.push({
        pathname: `/expertInfoController/getExpertDetails/{id}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'view',
          title: '查看专家信息',
          info: record,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onEdit: (record: Record<string, any>) => {
      history.push({
        pathname: `/expertInfoController/editExpert/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'edit',
          title: '编辑专家信息',
          info: record,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onAdd: () => {
      history.push({
        pathname: `/expertInfoController/addExpert/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'add',
          title: '添加专家信息',
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onCancel: (record: Record<string, any>) => {
      setInfo(record);
      setIsShowCancel(true);
    },
    onBatchImport: () => setBatchImport(true),
    onExport: () => setExportState(true),
  };

  const tableProps = {
    columns: getExpertsManageTableColumns(operation, curRes),
    dataSource: expertsManageDataSource,
    loading: expertsManageLoading,
    pagination: expertsManageTableProps.pagination as any,
    rowKey: 'id',
    onPageChange: (current: number, pageSize: number) => {
      expertsManageRun({ current, pageSize });
    },
    rowSelection: curRes?.['/expertInfoController/export']
      ? {
          type: 'checkBox',
          selectedRowKeys,
          onSelect: (record: any, selected: any) => {
            if (selected) {
              setSelectedRowKeys([...selectedRowKeys, record?.id]); // 保存key
              setSelectRows([...selectRows, record]); // 保存record
            } else {
              const rowsList = selectRows?.filter((item) => record?.id != item?.id);
              setSelectedRowKeys(rowsList?.map((i: Record<string, any>) => i?.id));
              setSelectRows(rowsList);
            }
          },
          onSelectAll: (selected: any, _: any, changeRows: any) => {
            let dataKeys: any[] = [];
            expertsManageDataSource?.forEach((item: Record<string, any>) => {
              dataKeys?.push(item?.id);
            });
            if (selected) {
              let keylist = Array.from(new Set([...dataKeys, ...selectedRowKeys]));
              setSelectedRowKeys(keylist);
              setSelectRows([...selectRows, ...changeRows]);
            } else {
              let newarr: any[] = selectedRowKeys?.filter((item) => {
                return !dataKeys?.includes(item);
              });
              setSelectedRowKeys(newarr);
              let keys: any[] = [];
              changeRows?.forEach((item: any) => {
                keys?.push(item?.id);
              });
              const newRows = selectRows?.filter((item) => {
                return keys?.indexOf(item?.id) == -1;
              });
              setSelectRows(newRows);
            }
          },
        }
      : undefined,
  };

  // 点击搜索和重置
  const searchClickFun = (params: Record<string, any>) => {
    setSelectRows([]);
    setSelectedRowKeys([]);
    expertsManageRun({ ...params });
  };

  const searchProps = {
    switchList: [],
    onSwitch: () => {},
    searchList: getExpertsManageSearchColumns(ExpertsDictionaryData),
    onSearch: (params) => searchClickFun(params),
    onReset: () => searchClickFun({}),
  };

  const actionList = getExpertsManageTableHeaderActions(operation, curRes);

  return {
    cancelForm,
    isShowCancel,
    cancelSubmit,
    setIsShowCancel,
    operation,
    tableProps,
    searchProps,
    actionList,
    batchImport,
    setBatchImport,
    expertsManageRun,
    exportState,
    setExportState,
    exportSearchParams,
    selectRows,
    selectedRowKeys,
  };
}
